<?php

namespace App\Http\Controllers\Data;

use App\Http\Controllers\Controller;
use App\Models\Honour;
use Illuminate\Http\Request;
use Validator;

class HonourController extends Controller
{
    public function SampleHonour()
    {
        $data = null;
        $re = Honour::orderBy('time', 'desc')->get();
        for ($i = 0; $i < sizeof($re); ++$i) {
            $data[$i]['cover_img'] = $re[$i]['cover_img'];
            $data[$i]['name'] = $re[$i]['name'];
            $data[$i]['id'] = $re[$i]['id'];
            // $data['categories'] = $re[$i]['categories'];
        }

        return json_encode($data);

        // fake data

        // $data['img']='./honour/00001.jpg';
        // $data['name']='IATF证书';
        // $data['id']='00001';
        // $data['categories']='公司荣誉';
        // return json_encode($data);;
    }

    public function NextHonour(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 401);
        }
        $data = Honour::where('id', '>', $request->id)->first();
        if ((bool) $data) {
            return json_encode($data);
        } else {
            $data = ['success' => false, 'message' => '已经是最后一个！'];

            return json_encode($data);
        }
    }

    public function CompleteHonour(Honour $honour)
    {
        $re = Honour::where('id', '=', $honour->id)
            ->first();
        $visits = $re['visits'];
        ++$visits;
        // var_dump($visits);
        Honour::where('id', '=', $honour->id)->update(['visits' => $visits]);

        return json_encode($honour);

        // fake data

        // $data['img']='./honour/00001.jpg';
        // $data['name']='IATF证书';
        // $data['id']='00001';
        // $data['visits']=1;
        // $data['time']='2019-7-2';
        // $data['categories']='公司荣誉';

        // return json_encode($data);
    }

    public function HonourInsert(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|max:10',
            'cover_img' => 'required',
            'u_id' => 'required',
            // 'categories' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 401);
        }

        $name = Honour::where('name', $request->name)
            ->first();
        if ($name) {
            session()->flash('false', '荣誉名称重复！');

            return redirect()->back();
        }

        $honour = $request->all();
        $honour['visits'] = 0;
        $honour['time'] = date('Y-m-d h:i:s', time());
        $res = Honour::create($honour);

        $totalCoverImg = glob('./temp/'.$request->u_id.'/honour/CoverImg'.'*');
        $CoverImgNumber = count($totalCoverImg);
        $CoverImg = $request->cover_img;
        if ($CoverImgNumber == 0) {
            $CoverImg = $request->cover_img;
        } else {
            $CoverImghandler = opendir('./temp/'.$request->u_id.'/honour/CoverImg');
            while (($CoverImgname = readdir($CoverImghandler)) !== false) {
                if ($CoverImgname != '.' && $CoverImgname != '..') {
                    $temp = explode('.', $CoverImgname);
                    $extension = end($temp);
                    $picName = $res['id'].'.'.$extension;
                    $CoverImg = './honour/CoverImg/'.$picName;
                    if (!file_exists($CoverImg)) {
                        $counter_file = $CoverImg;
                        $fopen = fopen($counter_file, 'wb '); //新建文件命令
                        fclose($fopen);
                    }
                    copy('./temp/'.$request->u_id.'/honour/CoverImg/'.'cover_img'.'.'.$extension, $CoverImg);
                }
            }
        }
        if ($CoverImg != $request->cover_img) {
            Honour::where('id', '=', $res['id'])
                ->update(['cover_img' => $CoverImg]);
        }

        if (file_exists('./temp/'.$request->u_id.'/honour/CoverImg')) {
            $dh = opendir('./temp/'.$request->u_id.'/honour/CoverImg');
            while ($file = readdir($dh)) {
                if ($file != '.' && $file != '..') {
                    $fullpath = './temp/'.$request->u_id.'/honour/CoverImg'.'/'.$file;
                    if (!is_dir($fullpath)) {
                        unlink($fullpath);
                    } else {
                        deldir($fullpath);
                    }
                }
            }
            closedir($dh);
        }
        if ($res) {
            session()->flash('true', '新增成功！');
            $data = ['success' => true, 'message' => '新增成功'];

            return json_encode($data);
        } else {
            Honour::destroy($request->id);
            session()->flash('false', '新增失败!');

            return redirect()->back();
        }
    }

    public function HonourUpdate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
            'name' => 'required|max:10',
            // 'categories'=> 'required|max:20',
            'u_id' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 401);
        }
        $honour = $request->all();
        unset($honour['u_id']);
        $honour_id = Honour::get();
        for ($i = 0; $i < sizeof($honour_id); ++$i) {
            if ($honour_id[$i]['name'] == $request->name) {
                if ($honour_id[$i]['id'] != $request->id) {
                    session()->flash('false', '此荣誉与其他荣誉名称重复');

                    return redirect()->back();
                }
            }
        }
        $cover_del = Honour::where('id', '=', $request->id)->first();
        if (isset($request->cover_img)) {
            if (file_exists($cover_del['cover_img'])) {
                unlink($cover_del['cover_img']);
            }
        }
        $totalCoverImg = glob('./temp/'.$request->u_id.'/honour/CoverImg'.'*');
        $CoverImgNumber = count($totalCoverImg);
        if ($CoverImgNumber != 0) {
            $CoverImghandle = opendir('./temp/'.$request->u_id.'/honour/CoverImg');
            while (($CoverImgname = readdir($CoverImghandle)) !== false) {
                if ($CoverImgname != '.' && $CoverImgname != '..') {
                    $temp = explode('.', $CoverImgname);
                    $extension = end($temp);
                    $picName = $request->id.'.'.$extension;
                    $CoverImg = './honour/CoverImg/'.$picName;
                    if (!file_exists($CoverImg)) {
                        $counter_file = $CoverImg;
                        $fopen = fopen($counter_file, 'wb '); //新建文件命令
                        fclose($fopen);
                    }
                    copy('./temp/'.$request->u_id.'/honour/CoverImg/'.'cover_img'.'.'.$extension, $CoverImg);
                    $honour['cover_img'] = $CoverImg;
                }
            }
        }
        unset($honour['id']);
        $original = Honour::where('id', '=', $request->id)->first();
        unset($original['id']);
        if ($original == $honour) {
            $data = ['success' => false, 'message' => '修改的内容与原先内容相同！'];

            return json_encode($data);
        }

        $re = Honour::where('id', $request->id)
            ->first();
        $re = Honour::where('id', '=', $request->id)->update($honour);
        if (file_exists('./temp/'.$request->u_id.'/honour/CoverImg')) {
            $dh = opendir('./temp/'.$request->u_id.'/honour/CoverImg');
            while ($file = readdir($dh)) {
                if ($file != '.' && $file != '..') {
                    $fullpath = './temp/'.$request->u_id.'/honour/CoverImg'.'/'.$file;
                    if (!is_dir($fullpath)) {
                        unlink($fullpath);
                    } else {
                        deldir($fullpath);
                    }
                }
            }
            closedir($dh);
        }
        if ($re) {
            session()->flash('true', '修改成功！');
            $data = ['success' => true, 'message' => '修改成功'];

            return json_encode($data);
        } else {
            session()->flash('false', '修改失败,无对应id!');

            return redirect()->back();
        }
    }

    public function HonourDelete(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 401);
        }

        $res = Honour::where('id', $request->id)->first();
        $re = Honour::where('id', '=', $request->id)->delete();
        if ($re) {
            if ((isset($res['cover_img']))) {
                if (file_exists($res['cover_img'])) {
                    unlink($res['cover_img']);
                }
            }
            session()->flash('true', '删除成功！');
            $data = ['success' => true, 'message' => '删除成功'];

            return json_encode($data);
        } else {
            session()->flash('false', '删除失败，无对应ID信息!');

            return redirect()->back();
        }
    }
}
